package yu.liu.personal.app.myapplication.ui;

import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.widget.ImageView;
import android.widget.TextView;

import java.lang.ref.WeakReference;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import butterknife.ButterKnife;
import yu.liu.personal.app.myapplication.R;
import yu.liu.personal.app.myapplication.ui.main.MainPage;
import yu.liu.personal.app.myapplication.utils.ResourceManager;

/**
 * Created by Administrator on 2016/9/24.
 */

public class StartupPage extends Activity {

    private ResourceManager resManager;

    @BindView(R.id.ivWelcome)
    ImageView ivWelcome;
    @BindView(R.id.tvVersionWelcome)
    TextView tvVersionWelcome;

    private Handler forwardHandler;
    private Timer forwardTimer;
    private TimerTask forwardTask;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        resManager = ResourceManager.getManager(this);
        setContentView(resManager.getResourceID("layout", "layout_welcome_page"));
        ButterKnife.bind(this);
        Random rand = new Random(System.currentTimeMillis());
        int index = rand.nextInt(2);
        index++;
        try {
            PackageManager pm = getPackageManager();
            PackageInfo pi = pm.getPackageInfo(getPackageName(), 0);
            String version = pi.versionName;
            tvVersionWelcome.setText(version);
        } catch (Exception e) {
            if(tvVersionWelcome != null) {
                tvVersionWelcome.setText("");
            }
            e.printStackTrace();
        }
        ivWelcome.setImageResource(resManager
                .getResourceID("mipmap", "pic_welcome_page_" + index));
        forwardHandler = new ForwardHandler(this);
        forwardTimer = new Timer();
        forwardTask = new ForwardTask();
        forwardTimer.schedule(forwardTask, 3000);
    }

    private static class ForwardHandler extends Handler {
        private WeakReference<StartupPage> actRef;

        public ForwardHandler(StartupPage activity) {
            actRef = new WeakReference<>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            StartupPage activity = actRef.get();
            // forward to main page
            Intent intent = new Intent(activity, MainPage.class);
            activity.startActivity(intent);
            activity.finish();
        }
    }

    private class ForwardTask extends TimerTask {
        @Override
        public void run() {
            if (forwardHandler != null) {
                forwardHandler.sendEmptyMessage(0);
            }
        }
    }
}
